package com.tianji.aigc.service.impl;

import cn.hutool.extra.spring.SpringUtil;
import com.tianji.aigc.agent.AbstractAgent;
import com.tianji.aigc.agent.Agent;
import com.tianji.aigc.config.SystemPromptConfig;
import com.tianji.aigc.enums.AgentTypeEnum;
import com.tianji.aigc.enums.ChatEventTypeEnum;
import com.tianji.aigc.service.ChatService;
import com.tianji.aigc.vo.ChatEventVO;
import lombok.RequiredArgsConstructor;
import org.springframework.ai.chat.client.ChatClient;
import org.springframework.stereotype.Service;
import reactor.core.publisher.Flux;

import java.util.Map;

/**
 * @author wys
 * @version V1.0
 * @date 2025-04-24 17:13
 */
@Service
@RequiredArgsConstructor
public class AgentServiceImpl implements ChatService {
    private final ChatClient openAiChatClient;
    private final SystemPromptConfig systemPromptConfig;


    /**
     * 聊天
     *
     * @param question  问题
     * @param sessionId 会话id
     * @return 回答内容
     */
    @Override
    public Flux<ChatEventVO> chat(String question, String sessionId) {
        Agent routeAgent = findAgentByType(AgentTypeEnum.ROUTE);
        String result = routeAgent.process(question, sessionId);
        Agent agentByType = findAgentByType(AgentTypeEnum.agentNameOf(result));
        if (agentByType == null) {
            ChatEventVO chatEventVO = ChatEventVO.builder()
                    .eventData(result)
                    .eventType(ChatEventTypeEnum.DATA.getValue()).build();
            return Flux.just(chatEventVO, AbstractAgent.STOP_EVENT);
        }
        return agentByType.processStream(question, sessionId);
    }

    /**
     * 停止生成
     *
     * @param sessionId 会话id
     */
    @Override
    public void stop(String sessionId) {
        findAgentByType(AgentTypeEnum.ROUTE).stop(sessionId);
    }

    /**
     * 根据代理类型查找对应的Agent实例
     *
     * @param agentTypeEnum 要查找的代理类型
     * @return 与给定类型匹配的Agent实例，如果未找到或类型为null则返回null
     */
    private Agent findAgentByType(AgentTypeEnum agentTypeEnum) {
        if (agentTypeEnum == null) {
            return null;
        }
        Map<String, Agent> beans = SpringUtil.getBeansOfType(Agent.class);
        // 遍历所有Agent Bean查找匹配类型
        for (Agent agent : beans.values()) {
            if (agentTypeEnum.equals(agent.getAgentType())) {
                return agent;
            }
        }
        return null;
    }

    /**
     * 文本对话
     *
     * @param question 问题
     * @return 回答
     */
    @Override
    public String chatText(String question) {
        return openAiChatClient.prompt()
                .system(promptSystem -> promptSystem.text(systemPromptConfig.getTextSystemMessage().get()))
                .user(question)
                .call()
                .content();
    }
}
